package org.app
package dao

import models.BookModel

import scala.collection.mutable.ListBuffer

// 图书，数据操作层
class BookDAO {
  // 加载图书。从文件中读入
  def loadBooks(): ListBuffer[BookModel] = {
    val books = new ListBuffer[BookModel]()
    val source = scala.io.Source.fromFile("books.txt")
    for(line <- source.getLines()){
      val Array(id,name,author,available) = line.split(",")
      // 实例化一本书，保存到List
      books += BookModel(id.toInt,name,author,available.toBoolean)
    }
    // 关闭连接
    source.close()
    books
  }

  // 保存图书。将图书写入文件
  def saveBooks(books: ListBuffer[BookModel]): Unit = {
    val writer = new java.io.PrintWriter(new java.io.File("books.txt"))
    for(book <- books){
      writer.println(book.id + "," + book.name + "," + book.author + "," + book.available)
    }
    writer.close()
  }
}
